package com.lefevre.cms.freemarker.directive;

import com.lefevre.cms.bean.theme.Forum;
import com.lefevre.cms.bean.theme.ThemeRunObject;
import com.lefevre.cms.service.theme.ThemeService;
import com.lefevre.cms.utils.threadLocal.TemplateThreadLocal;
import com.lefevre.cms.web.action.theme.TemplateMain;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模板自定义方法
 */
@Configuration
public class FunctionDirective implements TemplateDirectiveModel {

    @Resource
    ThemeService themeService;
    @Resource
    TemplateMain templateMain;

    private static BeansWrapper getBeansWrapper() {
        BeansWrapperBuilder builder = new BeansWrapperBuilder(freemarker.template.Configuration.VERSION_2_3_31);
        builder.setSimpleMapWrapper(true);//模板能使用Map方法
        return builder.build();
    }

    /**
     * @param env
     * @param params   参数
     * @param loopVars 循环变量
     * @param body     指令内容体
     */
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        //版块引用代码
        String referenceCode = "";
        String templatesDir = themeService.findTemplateDir_cache();
        ThemeRunObject themeRunObject = TemplateThreadLocal.get();
        //布局文件
        List<String> layoutFile = new ArrayList<>();
        //提交参数
        Map<String, Object> parameter = new HashMap<>();
        //运行时参数
        Map<String, Object> runtimeParameter = new HashMap<>();

        //取得当前正在运行的引入指令
        if (themeRunObject != null) {
            //引用代码
            referenceCode = themeRunObject.getReferenceCode();
            //布局文件
            layoutFile.addAll(themeRunObject.getLayoutFileList());
            if (themeRunObject.getParameter() != null && themeRunObject.getParameter().size() > 0) {
                parameter.putAll(themeRunObject.getParameter());
                themeRunObject.getParameter().clear();
            }
            if (themeRunObject.getRuntimeParameter() != null && themeRunObject.getRuntimeParameter().size() > 0) {
                runtimeParameter.putAll(themeRunObject.getRuntimeParameter());
            }
        }
        //取得<@function parameter...></@function>的参数
        if (params != null && params.size() > 0) {
            for (Object o : params.entrySet()) {
                Map.Entry ent = (Map.Entry) o;
                if (ent.getValue() != null && !"".equals(ent.getValue().toString().trim())) {
                    parameter.put(ent.getKey().toString(), ent.getValue().toString().trim());
                }
            }
        }
        if (referenceCode != null && !"".equals(referenceCode)) {
            //模板路径名称(env.getTemplate().getName()方法已过时)
            String templatePathName = env.getCurrentTemplate().getName();

            //模板文件名称  StringUtils.lastIndexOfIgnoreCase从后往前查，不区分大小写
            String name = templatePathName.substring(StringUtils.lastIndexOfIgnoreCase(templatePathName, "/") + 1, templatePathName.lastIndexOf("."));//删除后缀名

            Forum forum = themeService.findForum_cache(templatesDir, referenceCode);
            if (forum != null) {
                //版块模板前缀     ProductRelated_Product_Page
                StringBuffer modulePrefix = new StringBuffer("");
                String[] module_str = forum.getModule().split("_");
                int i = 0;
                for (String str : module_str) {
                    modulePrefix.append(str);
                    if (i < 2) {
                        modulePrefix.append("_");
                    } else {
                        break;
                    }
                    i++;
                }
                if (name.equals(forum.getModule()) && forum.getInvokeMethod().equals(1)) {//1.引用代码
                    if (layoutFile.contains(forum.getLayoutFile()) || forum.getLayoutType().equals(6)) {
                        env.setVariable(modulePrefix.toString(), getBeansWrapper().wrap(templateMain.templateObject(forum, parameter, runtimeParameter)));//引用代码为key  如:Product_Show_1
                        if (body != null) {
                            body.render(env.getOut());
                        }
                    }
                }
            }
        }
    }
}
